# -*- coding:utf-8 -*-
# __author__ : "张百科"
# Date: 2021/1/22 14:59
# File: user.py
# IDE: PyCharm
from rest_framework.viewsets import ModelViewSet,GenericViewSet
from serializers.user import UserDetailSerializer
from models.user import User
from rest_framework import filters
from django.contrib.auth.hashers import make_password,check_password
from coreapi import Field
import coreschema
import datetime
from rest_framework.decorators import action
from rest_framework.schemas import ManualSchema
from django_filters.rest_framework import DjangoFilterBackend
from utils.response.response import BaseResponse
from utils.Decorators.webworkdecorator import WorkDecorator
from utils.response.httpstate import *
from rest_framework import status
from utils.pagination import pagination,pageSerializer
class UserViewSet(GenericViewSet):

    queryset = User.objects.filter(is_delete=0,is_allowed_login=1)
    serializer_class = UserDetailSerializer
    filter_backends = (DjangoFilterBackend,filters.SearchFilter,filters.OrderingFilter)
    pagination_class =pagination.Pagination
    #filter_class = apifilters.EnterpriseFilter
    search_fields = ('user_name','login_name','mobile')

    @WorkDecorator(operate="用户管理", message='用户列表')
    def list(self, request,*args,**kwargs):

        queryset = self.filter_queryset(self.get_queryset())
        page_queryset = self.paginate_queryset(queryset)
        serializer = self.get_serializer(page_queryset, many=True)

        count = self.paginator.page.paginator.count  # 总数
        num = self.paginator.page.paginator.num_pages  # 页数
        page_size = self.paginator.get_page_size(request)  # 每页显示条数
        pageserializer = pageSerializer.Serializer({'count': count, 'page_num': num, 'page_size': page_size})

        return BaseResponse(data=serializer.data,page=pageserializer.data)

    @WorkDecorator(operate="用户管理", message='新增用户')
    def create(self, request,*args,**kwargs):

        data = request.data
        # 2.创建序列化器
        serializer = self.get_serializer(data=data)
        # 3.校验
        serializer.is_valid(raise_exception=True)
        # 4.保存
        serializer.save()
        # 5.返回响应
        return BaseResponse(data=serializer.data)

    @WorkDecorator(operate="用户管理", message='更新用户')
    def update(self, request,pk,*args,**kwargs):

        user = User.objects.filter(pk=pk).first()
        user_ser = UserDetailSerializer(user, data=request.data)

        if user_ser.is_valid():
            user_ser.save()
            return BaseResponse()
        else:
            return BaseResponse(message='错误', code=CODE_BUSSINESS_ERROR)
        # 5.返回响应


    @WorkDecorator(operate="用户管理", message='冻结用户')
    def destroy(self, request,pk,*args,**kwargs):
        # postData = request.data
        # id = postData['id']
        #
        # users=User.objects.filter(id=id,is_delete=0)
        # if users:
        #     user=users[0]
        #     user.is_delete=1
        #     user.save()
        #     serializer=self.get_serializer(user,many=False)
        #     return BaseResponse(data=serializer.data)
        # else:
        #     return BaseResponse(message='用户账号不存在或已停用', code=CODE_BUSSINESS_ERROR)

        user = User.objects.filter(pk=pk).first()
        user.is_delete=1
        user.save()
        return BaseResponse()


    @WorkDecorator(operate="用户管理", message='设置后台登录')
    @action(methods=['post'], detail=False, schema=ManualSchema(
        fields=[
            Field(name='id', required=True, location='form', schema=coreschema.Integer(description='用户ID')),
        ]))
    def allowed(self, request, *args, **kwargs):
        postData = request.data
        id = postData['id']

        users = User.objects.filter(id=id, is_delete=0)
        if users:
            user = users[0]
            is_allowed_login=user.is_allowed_login
            if is_allowed_login==1:
                user.is_allowed_login=0
            else:
                user.is_allowed_login=1
            user.save()
            #serializer = self.get_serializer(user, many=False)
            return BaseResponse()
        else:
            return BaseResponse(message='用户账号不存在或已停用', code=CODE_BUSSINESS_ERROR)

    @WorkDecorator(operate="用户管理", message='修改密码')
    @action(methods=['post'], detail=False, schema=ManualSchema(
        fields=[
            Field(name='id', required=True, location='form', schema=coreschema.Integer(description='用户ID')),
            Field(name='oldpass', required=True, location='form', schema=coreschema.String(description='旧密码')),
            Field(name='newpass', required=True, location='form', schema=coreschema.String(description='新密码')),
        ]))
    def chgpwd(self, request, *args, **kwargs):
        try:
            # postData = json.loads(request.body)
            postData = request.data
            id = postData['id']
            password = postData['oldpass']
            newpassword = postData['newpass']

            if id > 0 and len(password) > 0:
                # 根据名称获取用户信息
                if len(newpassword) > 4:
                    cur_user = User.objects.filter(id=id, is_delete=0).first()
                    if cur_user:
                        if check_password(password, cur_user.password):
                            result = UserDetailSerializer(cur_user)
                            userpass = make_password(newpassword)
                            cur_user.password = userpass
                            cur_user.save()
                            return BaseResponse(data=result.data)
                        else:

                            return BaseResponse(message='原密码输入不正确', code=CODE_BUSSINESS_ERROR)
                    else:
                        return BaseResponse(message='用户账号不存在或已停用', code=CODE_BUSSINESS_ERROR)
                else:
                    return BaseResponse(message='新密码长度不符合要求', code=CODE_BUSSINESS_ERROR)
            else:
                return BaseResponse(message='用户名或者密码为空', code=CODE_BUSSINESS_ERROR, status=status.HTTP_400_BAD_REQUEST)
        except Exception as ex:
            return BaseResponse(message=str(ex), code=CODE_BUSSINESS_ERROR, status=status.HTTP_400_BAD_REQUEST)